package org.zkMock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 *  主线程中添加元素到list中,zkWatcher监控到新添加元素时,
 *  获取并打印最新的元素,且只打印一次
 *
 *   由于ArrayList不是线程安全的.所以这里如果不休眠的话.
 *   latestEle有可能会是null.可以切换线程安全的容器
 */
@SuppressWarnings("all")
public class ZkWatchMock2 {

    private static ArrayList<String> list = new ArrayList<String>();

    public static void main(String[] args) throws Exception {

        new Thread(new Runnable() {
            boolean flag = true;
            String latestEle = null;
            volatile int listSize;

            // key为list的size,value为当前size-1的元素打印的次数
            // 所有主线程中的添加的最新元素,都在zkWatcher线程中只打印一次
            Map<Integer, Integer> map=new HashMap<>();

            public void run() {
                System.out.println("zkWatcher监控线程执行了");

                while (flag) {
                    if (getListSize() != 0) {
//                        System.out.println("进入if了");

                        latestEle = list.get( getListSize() - 1);
                        if (! map.keySet().contains(getListSize())) {
                            map.put(getListSize(), 1);
                            System.out.print("\nzk监控获取到最后元素是:" + this.latestEle +"\n");
                        }

                        if (latestEle == null) {
                            System.out.println("latestEle is "+latestEle +"----listSize:"+getListSize()  +" -------- list:"+list);
                        }

                        //由于ArrayList不是线程安全的.所以这里如果不休眠的话.
                        //latestEle有可能会是null
                        try {
                            Thread.sleep(10L);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        if (latestEle.equals("exit")) {
                            System.out.println("zkWatcher线程即将退出");
                            break;
                        }
                    }
                }

            }

            public int getListSize() {
                listSize = list.size();
                return listSize;
            }
        },"zkWatcher").start();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("请输入:");
            String line = scanner.nextLine();
            if (line.equals("exit")) {
                list.add(line);
                System.out.println("主线程即将退出");
                break;
            }

            list.add(line);
        }

    }
}